//
//  ALTabBarView.swift
//  ALSinaWeiBoSwift
//
//  Created by 柴瑞军 on 16/4/8.
//  Copyright © 2016年 myCompany. All rights reserved.
//

import UIKit

class ALTabBarView: UITabBar {
//定义闭包
    var composeClosure:(()->())?
    
//布局子控件的时候调用的方法:主要是为了布局tabbar
    override func layoutSubviews() {
        super.layoutSubviews()
        
//        tabbar的个数
//        let buttonCount = 5;
        
        let width = bounds.size.width/CGFloat(buttonCount)
        
        var index = 0
        
//        创建frame
//        let newFrame  = CGRect(x: 0, y: 0, width: width, height: frame.size.height)
//        遍历tabbar的所有的子控件
        for subView in subviews {
//            只想重新设置
            if subView.isKindOfClass(NSClassFromString("UITabBarButton")!) {
//                设置frame
                
                subView.frame = CGRect(x: width*CGFloat(index), y: 0, width: width, height: frame.size.height)
                index += 1
                if index==2 {
                    index += 1
                }
            }
        }
//        添加uibutton
        composeButton.frame = CGRect(x: 2*width, y: 0, width: width, height: frame.size.height)
    }
    
//    MARK: -点击按钮监听的事件,闭回调
//    @objc :让oc可以调用swift的方法系统默认会为所有的swift方法加上@objc,如果方法加上了private,系统就不在为我们添加@objc
    @objc private func didClickComposeButton(){
//    调用闭包
        composeClosure?()
    }
    
//    懒加载button
    private lazy var composeButton:UIButton = {
    
//        创建btn
        let btn = UIButton()
//      设置按钮的图片
        btn.setImage(UIImage.init(named: "tabbar_compose_icon_add"), forState: UIControlState.Normal)
        btn.setImage(UIImage.init(named: "tabbar_compose_icon_add_highlighted"), forState: UIControlState.Highlighted)
        
        
//        设置按钮的背景图片
        btn.setBackgroundImage(UIImage.init(named: "tabbar_compose_button"), forState: UIControlState.Normal)
        btn.setBackgroundImage(UIImage.init(named: "tabbar_compose_button_highlighted"), forState: UIControlState.Highlighted)
//        监听绑定事件
        btn.addTarget(self, action: #selector(ALTabBarView.didClickComposeButton), forControlEvents: UIControlEvents.TouchUpInside)
        
//        将按钮添加到tabbar上
        self.addSubview(btn)
        
        return btn
    }()
}
